package com.tiduyun.data.exchange.controller;

import java.io.Reader;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.tiduyun.data.exchange.model.GxVehicleDataExchangeResult;
import com.tiduyun.data.exchange.service.GxVehicleDataExchangeGatewayService;

import lombok.extern.slf4j.Slf4j;

@RestController
@RequestMapping("/openapi/gxVehicle")
@Slf4j
public class GxVehicleDataExchangeController {

    @Autowired
    @Qualifier("gxVehicleDataExchangeGatewayServiceImpl")
    private GxVehicleDataExchangeGatewayService gxVehicleDataExchangeGatewayService;

    @RequestMapping(path = "/gateway", method = RequestMethod.POST)
    public GxVehicleDataExchangeResult gateway(HttpServletRequest request, Reader bodyReader) {
        Map<String, Object> queryParams = loadQueryParams(request, "method", "charset", "version", "biz_app_id", "invoke_app_id",
                "utc_timestamp", "sign_type", "sign");

        String body = null;
        try {
            body = IOUtils.toString(bodyReader);
        } catch (Exception e) {
            log.error("Read body failed", e);
        }

        return gxVehicleDataExchangeGatewayService.execute(queryParams, body);
    }

    private Map<String, Object> loadQueryParams(HttpServletRequest request, String... paramNames) {
        Map<String, Object> queryParams = new HashMap<>();
        Set<String> inputParamNames = new HashSet<>();
        CollectionUtils.addAll(inputParamNames, request.getParameterNames());
        for (String paramName : paramNames) {
            if (inputParamNames.contains(paramName)) {
                queryParams.put(paramName, request.getParameter(paramName));
            }
        }
        return queryParams;
    }

}
